package com.wgn.reportquery.thread;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.impl.client.CloseableHttpClient;

import com.wgn.reportquery.cons.Const;
import com.wgn.reportquery.dao.ImportDaoImple;
import com.wgn.reportquery.http.QueryHttpClient;
import com.wgn.reportquery.model.Hospital;
import com.wgn.reportquery.model.InputObj;
import com.wgn.reportquery.model.Query;
import com.wgn.reportquery.model.Report;
import com.wgn.reportquery.model.ReportDate;
import com.wgn.reportquery.model.Reportdata;
import com.wgn.reportquery.rj.model.RJReport;
import com.wgn.reportquery.rj.model.RJReportInfo;
import com.wgn.reportquery.service.SignService;
import com.wgn.reportquery.utils.Importer;
import com.wgn.reportquery.utils.ReportUtils;

public class Deal implements Runnable {

	private ImportSkThread importSkThread;
	String userName;
	Importer im;
	ImportDaoImple importDaoImple;

	public Deal(ImportSkThread importSkThread) {
		// TODO Auto-generated constructor stub
		this.importSkThread = importSkThread;
		im = new Importer();
		this.userName = importSkThread.getObj().getUsername();
		importDaoImple = new ImportDaoImple();
	}

	String message;

	@Override
	public void run() {
		String url;
		List<Reportdata> datas;
		InputObj obj = importSkThread.getObj();
		if (null != obj) {
			String inputtype = importSkThread.getObj().getType();
			System.out.println("导入类型:" + inputtype);
			if (inputtype.equalsIgnoreCase("rj")) {
				int index = 0;
				List<String> cardlist = obj.getCardlist();
				for (String kh : cardlist) {
					ReportDate date = ReportUtils.getDate("");//wgn
					String start_time = date.getStart();// 往前推一年
					String end_time = date.getEdn();// 当前日期
					SignService ss = new SignService();
					List<RJReportInfo> reports = ss.getReport(
							obj.getUsername(), start_time, end_time, kh);

					for (RJReportInfo rinfo : reports)// 根据编号去取完整数据
					{
						// 1.看数据库里面有没有
						List<String> para = new ArrayList<String>();
						para.add(obj.getUsername());
						para.add(rinfo.getBgrq());
						String bgdh = rinfo.getBgdh();// 仁济原始报告代号
						String bgnum = ReportUtils.getRjNo(bgdh);// 转换为短的代号
						String sql = "SELECT * FROM DATAS a WHERE username=? AND reportdate = ? AND a.`REPORTNO` LIKE '%##%' "
								.replace("##", bgnum);// 用短的代号查
						boolean exist = importDaoImple.exists(sql, para);
						if (!exist) {// 如果存在记录，则忽略,否则找到详细数据
							++index;
							RJReport rp = ss.getSingleReport(obj.getUsername(),
									bgdh);// 用老的查
							List<Reportdata> rjreports = ReportUtils
									.transRjReportData(rp, rinfo.getBgrq(),
											bgdh);// 用老的入库
							importDaoImple.insert(rjreports, obj.getUsername());
						}
					}

				}
				System.out.println("转移仁济医院数据成功一共" + index + "条");

			} else {// 申康导入
				obj = importSkThread.getObj();
				try {
					importSkThread.addClient();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				List<String> clist=obj.getCardlist();
				for(String card:clist)
				{
					Query q=importSkThread.getQ();
					q.setCardId(card);
					importSkThread.setQ(q);
				String queryTable=importSkThread.getSkqueryTable();
				List<String> urls = importSkThread.getUrls(queryTable);
				List<Hospital>nos=importSkThread.getSkNos(queryTable);
				int num = 0;
				int wholesize = urls.size();
				try {
					for (int index = 0; index < wholesize; index++) {
						List<String> para = new ArrayList<String>();
						para.add(obj.getUsername());
						Hospital h=nos.get(index);
						String bgdh = h.getNum();// 报告代号
						String hname=h.getHospital_name();
						if(hname!=null&&hname.indexOf("仁济")>-1)
							bgdh=bgdh.substring(8);//仁济的报告号码截断
						String sql = "SELECT * FROM DATAS a WHERE username=? AND a.`REPORTNO` LIKE '%##%' "
								.replace("##", bgdh);// 用短的代号查
						boolean exist = importDaoImple.exists(sql, para);
						if (exist){//存在就忽略
							continue;
						} 
						url = urls.get(index);
						String wholeurl = Const.SK_REPORT_URL + url;
						System.out.println(wholeurl);
						QueryHttpClient client = importSkThread.getClient();
						String reporthtml = client.getHtmlSk(wholeurl);
						InputStream inputStream = new ByteArrayInputStream(
								reporthtml.getBytes("UTF-8"));
						datas = im.getData(inputStream, importDaoImple, url,
								userName);
						if (datas.size() == 0)
							continue;
						
						int count=importDaoImple.insert(datas, userName);
						if(0!=count)
						++num;
						// int count =(int) Math.floor((double)((index + 1) /
						// wholesize)
						// * 100);
						// NumberFormat formatter = new DecimalFormat("0.00");
						// Double x = new Double(((double) (index + 1))
						// / ((double) wholesize)) * 100;
						// String count = formatter.format(x);
						// importSkThread.update(count);

					}
					System.out.println("卡号"+card+",sk本次查到数据" + wholesize + ",导入条数" + num);
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println(userName + "转移数据失败!" + e.getMessage());

				}	
				}
				
			}

		}
		try {
			List<String> para=new ArrayList<String>();
			para.add(userName);
			importDaoImple.update("update G_USER set COUNT=0 where USERNAME=?", para);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
}
